package com.loan.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.loan.common.exception.ServiceException;
import com.loan.common.helper.LoginHelper;
import com.loan.system.domain.BankEntity;
import com.loan.system.domain.UserBankEntity;
import com.loan.system.mapper.BankMapper;
import com.loan.system.mapper.UserBankMapper;
import com.loan.system.service.UserBankService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author shiguang on 2022/9/19 15:08
 */
@Service
@RequiredArgsConstructor
public class UserBankServiceImpl implements UserBankService {

    private final UserBankMapper userBankMapper;

    private final BankMapper bankMapper;

    @Override
    public UserBankEntity getUserBank(Long userId) {
        UserBankEntity userBankEntity = userBankMapper.selectOne(new QueryWrapper<UserBankEntity>().eq("user_id", userId).eq("del_flag", "0").last("limit 1"));
        if (userBankEntity != null) {
            BankEntity bankEntity = bankMapper.selectById(userBankEntity.getBankId());
            userBankEntity.setName(bankEntity.getSimpleName());
            return userBankEntity;
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserBank(Long id, Long bankId, String bankNo, Long userId) {
        UserBankEntity userBankEntity = userBankMapper.selectById(id);
        if (!userBankEntity.getUserId().equals(userId)) {
            throw new ServiceException("操作错误");
        }
        if (!userBankEntity.getBankId().equals(bankId)) {
            userBankEntity.setBankId(bankId);
        }
        if (!userBankEntity.getBankNo().equals(bankNo)) {
            userBankEntity.setBankNo(bankNo);
            BankEntity bankEntity = bankMapper.selectById(bankId);
            userBankEntity.setSimpleName(bankEntity.getSimpleName());
        }
        userBankEntity.setUpdateTime(new Date());
        userBankEntity.setUpdateBy(LoginHelper.getLoginUser().getUsername());
        return userBankMapper.updateById(userBankEntity);
    }
}
